package com.heima.gateway.filter;

import com.heima.gateway.config.AuthProperties;
import com.heima.gateway.util.JwtTool;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author: Serendipity-li
 * @Date: 2024/8/1 - 15:37
 * @Description: 自定义登陆权限的校验
 */
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private  final AntPathMatcher antPathMatcher  = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求信息
        ServerHttpRequest request = exchange.getRequest();
        //2.获取请求路径
        RequestPath path = request.getPath();
        //3.判断请求路径中是否包含排除的请求，即是否放行
        if (isExclude(path.toString())) {
            //包括则放行
            return chain.filter(exchange);
        }

        String token = null;
        //4.获取请求头中的token
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
             token = headers.get(0);
        }

        //5.解析token获取用户信息
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            //如果不包括，返回前端401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.则向微服务传递用户信息，在请求头里面添加一个用户属性
        String userInfo = userId.toString();
        exchange.mutate().request(builder -> {
            builder.header("user-info", userInfo);
        }).build();

        //7.放行
        return chain.filter(exchange);
    }

    /*
     * @description: 同来判断，获取到请求的path是否与放行路径列表中的地址匹配
     * @author: louis-li
     * @date: 2024/8/1 16:14
     * @param: [path] 请求路径
     * @return: boolean
     **/
    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
